﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using CrmCustomInstallActions.CrmSdk;
using CrmCustomInstallActions.CrmSdk.Discovery;
using CrmCustomInstallActions.MetadataServiceSdk;


namespace CrmCustomInstallActions.Helpers
{
    internal class CrmAuthentication
    {
        private string _ServerUrl;

        public string ServerUrl
        {
            get { return _ServerUrl; }
            set { _ServerUrl = value; }
        }

        internal CrmAuthentication(string ServerUrl)
        {
            _ServerUrl = ServerUrl;
        }


        public OrganizationDetail[] GetOrganizations(ICredentials Credential, int AuthenticationType)
        {

            // STEP 1: Instantiate and configure the CrmDiscoveryService Web service.

            CrmDiscoveryService discoveryService = new CrmDiscoveryService();
            // discoveryService.UseDefaultCredentials = true;
            discoveryService.Credentials = Credential;
            discoveryService.Url = String.Format(_ServerUrl + (_ServerUrl.EndsWith("/") ? "" : "/") + "MSCRMServices/2007/{0}/CrmDiscoveryService.asmx", (AuthenticationType == 0 ? "AD" : ""));


            // STEP 2: Retrieve the organization name and endpoint Url from the
            // CrmDiscoveryService Web service.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            try
            {
                return (discoveryService.Execute(orgRequest) as RetrieveOrganizationsResponse).OrganizationDetails;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }




    }
}
